package cn.hl.hm.handler;

import cn.hl.hm.constants.AlipayConfig;
import cn.hl.hm.constants.PayMethod;
import cn.hl.hm.dao.TRechargeActivityMapper;
import cn.hl.hm.entity.Driver;
import cn.hl.hm.entity.RechargeRecoard;
import cn.hl.hm.entity.TRechargeActivity;
import cn.hl.hm.entity.UnifiedOrderRespose;
import cn.hl.hm.service.DriverService;
import cn.hl.hm.service.RechargeRecoardService;
import cn.hl.hm.util.alipay.AlipayCore;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayConstants;
import com.alipay.api.internal.util.AlipaySignature;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.vizhuo.utils.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import smsClient.TestSDKClient;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 支付宝APP支付handler
 * 
 * @author 大和
 *
 */
@Service
public class ZfbRecPayHandler extends PayHandler {

	private static final Logger logger = Logger.getLogger(ZfbRecPayHandler.class);
	@Autowired
	@Qualifier("alipayConfigRoad")
	private AlipayConfig alipayConfigRoad;
	@Autowired
	@Qualifier("alipayConfigRoadQYB")
	private AlipayConfig alipayConfigRoadQYB;
	
	@Autowired
	RechargeRecoardService rechargeRecoardService;
	@Autowired
	DriverService driverService;
	@Autowired
	TRechargeActivityMapper tRechargeActivityMapper;
	/**
	 * 处理支付宝支付请求
	 */
	@Override
	public Map<String, String> handler(Map<String, String> payMap) {
		
		String orderCode = payMap.get("rechargeCode");
		String orderInfo = payMap.get("orderInfo");
		String iosFlag = payMap.get("iosFlag");

		HashMap<String, String> map = new HashMap<String, String>(); ;
			if(StringUtils.isNotBlank(orderInfo)){
				String slipayParams;
				try {
					AlipayConfig config = alipayConfigRoad;

					if(iosFlag.equals("1")){
						config = alipayConfigRoadQYB;
					}
					logger.info(".....支付宝环境[配置参数]："+config.toString()+"签名方式： "+AlipayConstants.SIGN_TYPE_RSA2);
					slipayParams = AlipaySignature.rsa256Sign(orderInfo, config.privateKey, config.zfbCharset);
					
					map.put("orderCode", orderCode);
					map.put("sign", slipayParams);
					map.put("backUrl", config.backUrl);
					return map;

				} catch (AlipayApiException e) {
					e.printStackTrace();
					return map;
				}
				
			}else {
				return map;
			}
	}
	@Override
	protected void initHandler() {
		register(PayMethod.ROAD_ZFB_RECHARGE, ZfbRecPayHandler.class);
	}

	/**
	 * 回调请求
	 */
	@Override
	public Boolean callback(HttpServletRequest request, HttpServletResponse response) {
		try {
			logger.info("......[支付宝回调]开始......" );
			
			BufferedReader reader = request.getReader();
			String line = "";
			StringBuffer inputString = new StringBuffer();
			while ((line = reader.readLine()) != null) {
				inputString.append(line);
			}
			if (reader != null) {
				reader.close();
			}
			logger.info("......[支付宝回调]接收到的报文......" + inputString.toString());
			//String decode = URLDecoder.decode(inputString.toString());
			String decode =URLDecoder.decode(inputString.toString(), "utf-8");
			//URL解码
			logger.info("......[支付宝回调]接收到的报文URLDecoder解码后......" + decode);
			//编码 (不加这行会有乱码)
			String str = new String(decode.getBytes("UTF-8"), "utf-8");
			logger.info("......[支付宝回调]接收到的报文UTF-8->UTF-8解码后......" + str);
			
			Map<String, String> map = AlipayCore.str2map(str);
			
			
			
			String orderCode = map.get("out_trade_no");// 商户网站唯一订单号
			String userPaymentTime = map.get("gmt_payment");// 支付时间
			String paymentFlowAccount = map.get("trade_no");// 流水账号支付宝交易号
			String paymentNo = map.get("buyer_logon_id");// 支付账号买家支付宝账号
			String sign = map.get("sign");
			AlipayConfig config = alipayConfigRoad;

			
			//验证签名
//			boolean rsaCheckContent = AlipaySignature.rsaCheckV1(map, config.publicKey, alipayConfigRoad.zfbCharset,AlipayConstants.SIGN_TYPE_RSA2);
//			logger.info("...支付宝验签结果："+rsaCheckContent);
//			if(!rsaCheckContent){
//				return false;
//			}
			
			 
			if(!map.get("trade_status").equalsIgnoreCase("TRADE_SUCCESS")){
				return false;
			}
			logger.info("......[支付宝验签结果成功]+[交易状态成功]......");
			UnifiedOrderRespose unifiedOrderRespose = new UnifiedOrderRespose();
			unifiedOrderRespose.setTime_end(userPaymentTime);
			unifiedOrderRespose.setTransaction_id(paymentFlowAccount);
			unifiedOrderRespose.setOpenid(paymentNo);
			unifiedOrderRespose.setOut_trade_no(orderCode);
			unifiedOrderRespose.setSign(sign);
			return processBusiness( unifiedOrderRespose);
		} catch (Exception ex) {
			ex.printStackTrace();
			return false;

		}

	}

	private Boolean processBusiness(UnifiedOrderRespose unifiedOrderRespose) {
		// 查订单
		RechargeRecoard orderParam = new RechargeRecoard();
		orderParam.setRechargeCode(unifiedOrderRespose.getOut_trade_no());
		List<RechargeRecoard> selectOrder = rechargeRecoardService.selectRechargeRecoard(orderParam);
		RechargeRecoard order = null;
		if(selectOrder!=null&&selectOrder.size()>0){
		
		}else {
			return false;
		}
		if (selectOrder != null && selectOrder.size() > 0) {
			order = selectOrder.get(0);
			logger.info("......[支付宝回调]开始处理业务......unifiedOrderRespose"+unifiedOrderRespose.toString());

			if (order.getStatus().equals("1")) {
				String userPaymentTime = unifiedOrderRespose.getTime_end();// 支付时间
				logger.info("支付时间" + userPaymentTime);
				if (userPaymentTime != null && !("null".equals(userPaymentTime))) {

				} else {
					userPaymentTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
				}
				Date string2Date = DateUtil.string2Date(userPaymentTime, "yyyy-MM-dd HH:mm:ss");
				logger.info("......转换后支付时间" + string2Date);

				return updateOrder(order, string2Date);
			

			} else {
				return true;
			}

		} else {
			return false;
		}
	}
	private Boolean updateOrder(RechargeRecoard order, Date string2Date) {
		// 1 修改订单
		RechargeRecoard orderParam2 = new RechargeRecoard();
		orderParam2.setUpdateTime(string2Date);
		orderParam2.setStatus("2");
		orderParam2.setId(order.getId());
		orderParam2.setType(2);
		int updateRechargeRecoard = rechargeRecoardService.updateRechargeRecoard(orderParam2);
		if(updateRechargeRecoard>0){
			//driver money
			Driver driver = new Driver();
			driver.setRemainCash(order.getRemainCash());
			driver.setId(order.getDriverId());
			
			int res = driverService.updateDriver(driver);
				if(res>0){
					//发短信
					TRechargeActivity tRechargeActivity = tRechargeActivityMapper.selectByPrimaryKey(order.getRechargeActivityId());
					if(tRechargeActivity!=null){
						if(order.getUserphone()!=null){
							SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日HH时mm分ss秒");
							String format = sdf.format(new Date());
							//TestSDKClient.testSendSMSE(order.getUserphone(), "【华凌叮当到】温馨提示您，您的账户于"+format+"通过支付宝充值"+tRechargeActivity.getAmount()+"元，活动奖励"+tRechargeActivity.getGiftAmount()+"元，账户余额"+order.getRemainCash()+"元【华凌叮当到：400-998-3903】");
							try {
								SendSmsRequest smsRequest = new SendSmsRequest();
								smsRequest.setTemplateParam("{\"rechargeAmount\":\""+tRechargeActivity.getAmount()+"\",\"giftAmount\":\""+tRechargeActivity.getGiftAmount()+"\",\"remainCash\":\""+order.getRemainCash()+"\",\"currentDate\":\""+format+"\"}");
								TestSDKClient.sendSmsByAli("SMS_110485051",smsRequest,order.getUserphone(),"华凌叮当到");
							}  catch (Exception e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						
						}
						
					}else {
						SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日HH时mm分ss秒");
						String format = sdf.format(new Date());
						SendSmsRequest smsRequest = new SendSmsRequest();
						smsRequest.setTemplateParam("{\"rechargeAmount\":\""+order.getAmount()+"\",\"remainCash\":\""+order.getRemainCash()+"\",\"currentDate\":\""+format+"\"}");
						TestSDKClient.sendSmsByAli("SMS_112485177",smsRequest,order.getUserphone(),"华凌叮当到");
					}
					
					return true;
				}else {
					return false;
				}
		}else {
			return false;
		}
	}

}
